package com.xx.sg.controller;

import com.fasterxml.jackson.core.JsonFactory;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonToken;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.xx.sg.own.entity.Road;
import com.xx.sg.own.service.RoadService;
import com.xx.sg.util.R;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.io.File;
import java.io.IOException;


@RestController
@RequestMapping("/road")
@Tag(name = "道路信息", description = "道路信息Api")
public class RoadController {

    @Autowired
    private RoadService roadService;

    @GetMapping("/inCircleRoads")
    @Operation(summary = "获取与圆相交的道路", description = "获取与圆相交的道路")
    public R inCircleRoads(@RequestParam Double longitude, @RequestParam Double latitude, @RequestParam Double radius) {
        return R.success(roadService.getRoadByCircle(longitude, latitude, radius));
    }

    //@GetMapping("/load")
    public R loadRoad() {
        File folder = new File("C:\\Users\\79055\\Desktop\\sip\\林区道路geojson"); // 替换为你的目录路径

        File[] files = folder.listFiles(File::isFile); // 只获取文件
        if (files != null) {
            for (File file : files) {
                String regionName = removeFileExtension(file.getName());
                loadFile(file, regionName);
            }
        }

        return R.success();
    }


    private void loadFile(File file, String regionName) {

        try {
            //  创建 JsonFactory 和 JsonParser（流式解析）
            JsonFactory factory = new JsonFactory();
            JsonParser parser = factory.createParser(file);

            // 创建 ObjectMapper（用于映射 Java Bean）
            ObjectMapper objectMapper = new ObjectMapper();

            // 定位到 "features" 数组
            while (!parser.isClosed()) {
                JsonToken token = parser.nextToken();

                if (JsonToken.FIELD_NAME.equals(token) && "features".equals(parser.getCurrentName())) {
                    parser.nextToken(); // 进入数组

                    // 遍历 "features" 数组，每次读取一个 Feature 对象
                    while (parser.nextToken() != JsonToken.END_ARRAY) {
                        JsonNode featureNode = objectMapper.readTree(parser);  // 读取每个 feature 为 JsonNode

                        featureNode.fields().forEachRemaining(entry -> {
                            if ("null".equals(entry.getValue().asText().trim())) {
                                System.err.println(entry.getValue().asText());
                                ((ObjectNode) featureNode).put(entry.getKey(), (String) null);  // 将 "null" 字符串转换为 null
                            }
                        });

                        JsonNode geometryNode = featureNode.get("geometry");
                        Road road = Road.builder()
                                .regionName(regionName)
                                .build();
                        roadService.save(road);
                        String wkt = formatGeometryWKT(geometryNode);
                        roadService.updateGeometry(road.getId(), wkt);
                    }
                }
            }

            parser.close(); // 关闭解析器，释放资源

        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }


    private String removeFileExtension(String fileName) {
        int lastDotIndex = fileName.lastIndexOf(".");
        if (lastDotIndex == -1) {
            return fileName; // 没有扩展名
        }
        return fileName.substring(0, lastDotIndex).replaceAll("道路", "");
    }

    private String formatGeometryWKT(JsonNode geometryNode) {

        String type = geometryNode.get("type").asText();
        // 获取坐标数组
        StringBuilder wkt = new StringBuilder();
        if ("LineString".equals(type)) {
            JsonNode coordinatesNode = geometryNode.get("coordinates");
            if (!coordinatesNode.isArray()) return "";

            wkt.append("LINESTRING(");
            appendCoordinateList(wkt, coordinatesNode);
            wkt.append(")");
        } else if ("MultiLineString".equalsIgnoreCase(type)) {
            JsonNode coordinatesNode = geometryNode.get("coordinates");
            if (!coordinatesNode.isArray()) return "";

            wkt.append("MULTILINESTRING(");
            for (int i = 0; i < coordinatesNode.size(); i++) {
                JsonNode line = coordinatesNode.get(i);
                if (!line.isArray()) continue;

                wkt.append("(");
                appendCoordinateList(wkt, line);
                wkt.append(")");

                if (i < coordinatesNode.size() - 1) {
                    wkt.append(", ");
                }
            }
            wkt.append(")");
        }
        return wkt.toString();
    }

    private void appendCoordinateList(StringBuilder wkt, JsonNode coordinates) {
        for (int i = 0; i < coordinates.size(); i++) {
            JsonNode coord = coordinates.get(i);
            if (coord.size() < 2) continue;
            wkt.append(coord.get(0).asText()).append(" ").append(coord.get(1).asText());
            if (i < coordinates.size() - 1) {
                wkt.append(", ");
            }
        }
    }
}
